[Note] webpack5 problem: Cannot GET/


Posted by urlun0404 on 2022-11-14

先記錄一下前陣子遇到一堆React-Router-Dom在webpack上使用的組態設定問題。


devServer: { historyApiFallback: true}

我用React-Router設定404 error的路由,如圖,亂打一串路徑的結果直接得到 "cannot GET /111111",而不是跳到我寫好的404頁面。

簡單來說,原因在於webpack server會先處理這個請求,但server沒有找到這條路徑就會先給一個無法處理的回應。


關於這個問題,官方文件也清楚地寫到:

When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. Enable devServer.historyApiFallback by setting it to true

所以,如果=希望處理404錯誤的方式是跳到特定頁面,而不是交給webpack server來處理,如同標題,要在webpack.config檔案組態設定的 devServer 加上 historyApiFallback: true

module.exports = {
  //...
  devServer: {
    historyApiFallback: true,
  },
};


另外,有一篇stackoverflow解答說也要加上 output.publicPath: '/',但我沒加上這條就可以處理404的問題🤔

不過沒加上 output.publicPath: '/' 倒是會碰到另一個跟相對路徑有關的問題,這個留在另一篇記錄:[Note] webpack 5 problem: Refused to execute script because its MIME type ('text/html') is not executable



後記
記錄References附上的一篇stackoverflow問題,跟我的狀況有點不同,解答是用 <base href="%PUBLIC_URL%/">,但是我在HTML文件加上這個反而會在webpack出錯。



References


#Webpack #webpack5 #problem #note #route #router #react-router-dom







Related Posts

用 Node.js 快速打造 RESTful API

用 Node.js 快速打造 RESTful API

[BE201] 後端中階:ORM 與 Sequelize

[BE201] 後端中階:ORM 與 Sequelize

VS code 段落過長怎麼辦?

VS code 段落過長怎麼辦?


Comments